package com.xiaoling.robot;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xiaoling.robot.bean.Msg;

import java.util.List;

public class ChatAdapter extends ArrayAdapter<Msg> {
    private int resourceId;
    private Context context;
    private List<Msg> data;

    public ChatAdapter(Context context, int resourceId, List<Msg> data) {
        super(context, resourceId, data);
        this.context = context;
        this.data = data;
        this.resourceId = resourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Msg message = data.get(position);
        ViewHolder holder;
        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.item, parent, false);
            holder = new ViewHolder();
            holder.leftLinearLayout = convertView.findViewById(R.id.leftLinearLayout);
            holder.rightLinearLayout = convertView.findViewById(R.id.rightLinearLayout);
            holder.leftMessage = convertView.findViewById(R.id.leftMessage);
            holder.rightMessage = convertView.findViewById(R.id.rightMessage);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (message.getStatus() == 0) {
            holder.leftLinearLayout.setVisibility(View.VISIBLE);
            holder.rightLinearLayout.setVisibility(View.GONE);
            holder.leftMessage.setText(message.getContent());
        } else {
            holder.leftLinearLayout.setVisibility(View.GONE);
            holder.rightLinearLayout.setVisibility(View.VISIBLE);
            holder.rightMessage.setText(message.getContent());
        }

        return convertView;
    }

    private static class ViewHolder {
        LinearLayout leftLinearLayout;
        LinearLayout rightLinearLayout;
        TextView leftMessage;
        TextView rightMessage;
    }
}
